package cn.hbwe.service.impl;

import cn.hbwe.pojo.entity.Department;
import cn.hbwe.mapper.DepartmentMapper;
import cn.hbwe.pojo.entity.Doctor;
import cn.hbwe.service.IDepartmentService;
import cn.hbwe.service.IDoctorService;
import cn.hbwe.util.CustomException;
import cn.hbwe.util.MessageConstant;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 7组
 * @since 2023-10-18
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    @Autowired
    private IDoctorService doctorService;

    @Transactional
    @Override
    public void removeDepartment(Integer id) {
        LambdaQueryWrapper<Doctor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(id != null, Doctor::getDepartmentId, id);
        long count = doctorService.count(lqw);

        //如果关联了医生,则不能删除
        if (count>0) {
            throw new CustomException(MessageConstant.EXISTS_DOCTOR);
        }

        this.removeById(id);
    }
}
